package com.eu.chipin;

import java.util.ArrayList;

import com.eu.chipin.backend.ContactPicker;
import com.eu.chipin.backend.DataType;
import com.eu.chipin.backend.Member;
import com.eu.chipin.backend.Trip;
import com.eu.chipin.backend.db.DB;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class NewTripActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_trip);

    Button addPeople = (Button) findViewById(R.id.button1);
    addPeople.setOnClickListener(new OnClickListener() {

      public void onClick(View v) {
        Intent intent = new Intent(NewTripActivity.this, ContactPicker.class);
        startActivityForResult (intent, 1);
      }
    });

    Button doneButton = (Button) findViewById(R.id.button2);
    doneButton.setOnClickListener(new OnClickListener() {

      public void onClick(View v) {
        ListView contactList = (ListView)findViewById(R.id.listView1);
        EditText tripTitle = (EditText)findViewById(R.id.editText1);
        ArrayAdapter<Member> adapter = (ArrayAdapter<Member>) contactList.getAdapter();
        if (adapter != null) {
          ArrayList<Member> members = new ArrayList<Member>();
          for (int i = 0, j = adapter.getCount(); i < j; i++) {
            members.add(adapter.getItem(i));
          }
          String title = tripTitle.getText().toString();
          if (!members.isEmpty() && !title.isEmpty()) {
            Trip trip = new Trip(title, members);
            DB.addTrip(NewTripActivity.this, trip);
            setResult(RESULT_OK);
            finish();
          }
        }
      }
    });

  }

  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
      ArrayList<Member> members = (ArrayList<Member>) data.getExtras().get(DataType.ContactsList.toString());
      ArrayAdapter<Member> membersAdapter = new ArrayAdapter<Member>(NewTripActivity.this, android.R.layout.simple_list_item_1, members);
      ListView contactList = (ListView)findViewById(R.id.listView1);
      contactList.setAdapter(membersAdapter);
    }
  }


  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_new_trip, menu);
    return true;
  }
}
